import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../shared/organization-unit-tree.component';
import { ProcessingDeliverySubCreateComponent } from '../ProcessingDeliveryCreate/ProcessingDeliverySubCreate/ProcessingDeliverySubCreate.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { ProfileServiceProxy, OutsourcingWorkflowServiceProxy, TaskServiceProxy, WorkflowServiceProxy, ProcessingDeliveryDto, ProcessingDeliveryViewDto, ProcessingDeliveryInputDto, ProcessingDeliveryStepUserDto, UserServiceProxy } from '@shared/service-proxies/service-proxies';
import { from } from 'rxjs';
import { SelectItem } from 'primeng/api';


@Component({
    selector: 'ProcessingDeliveryCreate',
    templateUrl: './ProcessingDeliveryCreate.component.html',
    styleUrls: ['./ProcessingDeliveryCreate.component.css']
})
export class ProcessingDeliveryCreateComponent extends AppComponentBase {
    @ViewChild('ProcessingDeliverySubCreate') ProcessingDeliverySubCreate: ProcessingDeliverySubCreateComponent;
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('teskdataTable') teskdataTable: Table;

    active = false;
    saving = false;
    filterText = '';
    selectedCar3: string;
    index = 0;
    isReadStr = [];
    isReadonlyed = false;

    stepusers: ProcessingDeliveryStepUserDto;
    users: SelectItem[];

    detailsprimengTableHelper: PrimengTableHelper;
    _processingDeliveryViewDto: ProcessingDeliveryViewDto[];
    clonedOutsourcings: { [s: number]: ProcessingDeliveryViewDto; } = {};
    selectProcessingDeliveryViewDto: ProcessingDeliveryViewDto[];

    _processingDelivery: ProcessingDeliveryDto = new ProcessingDeliveryDto();
    constructor(injector: Injector,
        private _outSourcingworkflowServiceProxy: OutsourcingWorkflowServiceProxy,
        private _taskServiceProxy: TaskServiceProxy,
        private _userService: UserServiceProxy,
        private _workflowService: WorkflowServiceProxy
    ) {
        super(injector);
        this.detailsprimengTableHelper = new PrimengTableHelper();
        this.stepusers = new ProcessingDeliveryStepUserDto();
    }
    // tslint:disable-next-line: use-life-cycle-interface
    ngOnInit(): void {



    }
    show(): void {



        this.active = true;


        this.modal.show();
    }
    close(): void {
        this.active = false;
        this.modal.hide();
    }
    onShown(): void {
        this._userService.getAllUserForDropDown2().subscribe(resultdata => {
            console.log(resultdata);
            this.users = resultdata;
        });
        this.index = 0;
        this.filterText = '';
        this.getTasks();
        this._processingDelivery = new ProcessingDeliveryDto();
        this.detailsprimengTableHelper.totalRecordsCount = 0;
        this.detailsprimengTableHelper.records = new Array();
        this.detailsprimengTableHelper.hideLoadingIndicator();
    }
    getTasks(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._outSourcingworkflowServiceProxy.getProcessingDeliveryByCode(
            this.filterText,
            //this.primengTableHelper.getSorting(this.dataTable),
            'Code',
            // this.primengTableHelper.getMaxResultCount(this.paginator, event),
            10,
            //this.primengTableHelper.getSkipCount(this.paginator, event),
            0
        )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                console.log(result);
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    //依据申请单获取任务
    SelectTask(record) {
        this._processingDelivery.productionUnit = record.applyUnit;
        this._processingDelivery.supplierUnit = record.supplierUnit;
        this._processingDelivery.requisitionCode = record.requisitionCode;
        this._processingDelivery.orderCode = record.orderCode;
        this._outSourcingworkflowServiceProxy.getProcessingDeliveryDtoByWorkflowId(record.workflowId).subscribe(dto => {
            console.log(dto);
            this._processingDeliveryViewDto = dto;
            this.detailsprimengTableHelper.totalRecordsCount = dto.length;
            this.detailsprimengTableHelper.records = dto;
            this.detailsprimengTableHelper.hideLoadingIndicator();

            this.isReadStr = new Array();

            _.forEach(dto, viewItem => {
                //viewItem.processingId = record.id;
                console.log(viewItem.taskForModelId);
                this._taskServiceProxy.getTaskForEdit(viewItem.taskForModelId)
                    .subscribe(userResult => {
                        viewItem.taskCode = userResult.taskCode;
                        viewItem.taskName = userResult.drawingName;
                        viewItem.picNo = userResult.drawingCode;
                    });
                this._outSourcingworkflowServiceProxy.getProcessingDeliveryAmountForTaskId(viewItem.processingOrderId, viewItem.taskForModelId)
                    .subscribe(result => {
                        viewItem.deliveredAmount = result;
                    });
            });
        }); 
        this._outSourcingworkflowServiceProxy.buildProcessingDeliveryCodeByOutsourcingCode(record.requisitionCode, record.orderCode).subscribe(code => {
            this._processingDelivery.deliveryCode = code;
          });
        this.index = 1;
    }
    handleChange(e) {
        this.index = e.index;
        console.log(this.index);
    }

    onRowEditInit(dto: ProcessingDeliveryViewDto) {
        console.log(dto);
        this.clonedOutsourcings[dto.taskForModelId.toString()] = { ...dto };
    }
    //保存行编辑
    onRowEditSave(dto: ProcessingDeliveryViewDto) {
        console.log(dto);

        delete this.clonedOutsourcings[dto.taskForModelId.toString()];
        this.selectProcessingDeliveryViewDto = new Array();
        let _current = this.selectProcessingDeliveryViewDto.find((element) => (element.taskForModelId === dto.taskForModelId));
        if (_current === undefined) {
            dto.deliveryDate = dto.deliveryDate;
            dto.passedAmount = dto.passedAmount;
            dto.quantityAmount = dto.quantityAmount;
            dto.noPassedAmount = dto.noPassedAmount;
            dto.qualityControlCardNo = dto.qualityControlCardNo;
            dto.deliveryAmount = dto.passedAmount + dto.quantityAmount + dto.noPassedAmount;
            const date1: any = dto.progressRequest; // the date you already commented/ posted
            const date2: any = dto.deliveryDate;    // today

            let r = {}; // object for clarity
            let message: string;

            const diffInSeconds = (date2 - date1) / 1000;
            const days = Math.floor(diffInSeconds / 60 / 60 / 24);
            if (days > 0) { //逾期
                dto.overdueDay = days;
                dto.isOverdue = true;
            } else {
                dto.overdueDay = 0;
                dto.isOverdue = false;
            }
            this.selectProcessingDeliveryViewDto.push(dto);
        } else {
            _current.deliveryAmount = dto.deliveryAmount;
        }
    }
    //取消行编辑
    onRowEditCancel(dto: ProcessingDeliveryViewDto, index: number) {
        console.log(this.clonedOutsourcings[dto.taskForModelId.toString()]);
        this._processingDeliveryViewDto[index] = this.clonedOutsourcings[dto.taskForModelId.toString()];
        delete this._processingDeliveryViewDto[dto.taskForModelId];
    }

    save() {
        console.log(this._processingDelivery);
        console.log(this._processingDeliveryViewDto);
        let input = new ProcessingDeliveryInputDto();
        let processingDeliveryViewDtos = new Array();

        _.forEach(this._processingDeliveryViewDto, viewitem => {
            let quantityAmount = viewitem.quantityAmount ? viewitem.quantityAmount : 0;
            let deliveryAmount = viewitem.deliveryAmount ? viewitem.deliveryAmount : 0;
            let noPassedAmount = viewitem.noPassedAmount ? viewitem.noPassedAmount : 0;
            console.log(quantityAmount);
            console.log(deliveryAmount);
            console.log(noPassedAmount);
            if ((quantityAmount + deliveryAmount + noPassedAmount) > 0) {
                processingDeliveryViewDtos.push(viewitem);
            }
        });

        if (processingDeliveryViewDtos.length === 0) {
            this.notify.info('未填写交货单明细');
            this.saving = false;
            return;
        }

        //判断审批用户是否设置
        if (!this.stepusers.qualityDepartmentManager||this.stepusers.qualityDepartmentManager==='-1') {
            this.notify.info('请选择质量处主管');
            this.saving = false;
            return;
        }
        if (!this.stepusers.workShopManager||this.stepusers.workShopManager==='-1') {
            this.notify.info('请选择车间主管');
            this.saving = false;
            return;
        }
        if (!this.stepusers.workShopLeader||this.stepusers.workShopLeader==='-1') {
            this.notify.info('请选择车间领导');
            this.saving = false;
            return;
        }
        if (!this.stepusers.qualityDepartmentLeader||this.stepusers.qualityDepartmentLeader==='-1') {
            this.notify.info('请选择质量管理处处长');
            this.saving = false;
            return;
        }

        input.stepUserDto = this.stepusers;
        input.processingDeliveryDto = this._processingDelivery;
        input.processingDeliveryViewDtos = this._processingDeliveryViewDto;
        this.saving = true;

        console.log(input);
        this._outSourcingworkflowServiceProxy.createOrUpdateProcessingDeliveryWorkFlow(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.close();
            });
    }
}
